package com.wm.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wm.reggie.common.R;
import com.wm.reggie.entity.User;
import com.wm.reggie.service.UserService;
import com.wm.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户发送短信
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();

        if (StringUtils.isNotEmpty(phone)){
            //生成随机的四位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);

            //调用阿里云提供的短信服务api完成发送短信
            //SMSUtils。sendMessage("瑞吉外卖","",phone,code)

            //需要将生成的验证码保存到session中
//            session.setAttribute(phone,code);

            //将生成的验证码缓存到redis中，并设置有效期为5分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

            return R.success("手机验证码短信发送成功");

        }
        return R.error("短信发送失败");
    }
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){

//        log.info("user {}, session {}",map,session);
        //获得手机号
        String phone =  map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();

        //从session中获取验证码
//        Object codeInSession = session.getAttribute(phone);

        //从Redis中获取缓存的验证码
        Object codeInSession = redisTemplate.opsForValue().get(phone);

        //session和传过来的code进行比较
        if(codeInSession != null && codeInSession.equals(code)){
            //如果能够对比成功，说明登录成功
            //判断当前手机号对应的用户是否为新用户，如果是新用户就自动完成注册
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(StringUtils.isNotBlank(phone), User::getPhone, phone);
            User userServiceOne = userService.getOne(lambdaQueryWrapper);
            User user = new User();
            if (userServiceOne == null) {
                user.setStatus(1);
                user.setPhone(phone);
                userService.save(user);
                session.setAttribute("user",user);
            }else {
                session.setAttribute("user",userServiceOne);
                user = userServiceOne;
            }
            //如果登录成功，删除Redis中的缓存
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("登录失败");
    }
}
